package com.adam.example.aggregation.metric;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.aggregations.*;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.adam.example.ElasticsearchClientHolder;

import java.io.IOException;
import java.util.List;

public class PercentilesAggregationExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient client = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        SearchResponse<Void> searchResponse = client.search(builder -> builder
                        .index("test_books")
                        .size(0)
                        .aggregations("agg", aggregationBuilder -> aggregationBuilder
                                .percentiles(percentilesAggregationBuilder -> percentilesAggregationBuilder
                                        .field("price")
//                                        .tdigest(tDigestBuilder -> tDigestBuilder  //默认算法，足以应对大多数场景，极端百分位计算效果不如hdr
//                                                .compression(100)  //压缩参数，值越大，精度越高。默认值100，通常在10-1000取值
//                                        )
                                        .hdr(hdrMethodBuilder -> hdrMethodBuilder  //更加精确，极端百分位计算效果好
                                                 .numberOfSignificantValueDigits(3)  //有效数字位数，值越大，精度越高。默认值3，可以在1-5取值
                                        )
                                        .keyed(false)
                                )
                        )
                , Void.class
        );
        Aggregate aggregate = searchResponse.aggregations().get("agg");
//        TDigestPercentilesAggregate tDigestPercentilesAggregate = aggregate.tdigestPercentiles();
//        Percentiles percentiles = tDigestPercentilesAggregate.values();
        HdrPercentilesAggregate hdrPercentilesAggregate = aggregate.hdrPercentiles();
        Percentiles percentiles = hdrPercentilesAggregate.values();
        List<ArrayPercentilesItem> arrayPercentilesItemList = percentiles.array();
        for(int i=0;i<arrayPercentilesItemList.size();i++) {
            ArrayPercentilesItem arrayPercentilesItem = arrayPercentilesItemList.get(i);
            System.out.println("[" + (i+1) + "]" + arrayPercentilesItem.key() + "%:" + arrayPercentilesItem.value());
        }

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
